package com.bawei.module_moto_circle.ui.post

import androidx.paging.Pager
import androidx.paging.PagingConfig
import com.bawei.module_moto_circle.http.MotoCircleApi
import com.bawei.module_moto_circle.http.MotoCircleNetModule
import com.bawei.module_moto_circle.ui.post.paging.PostPageSource
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.flow.flowOn
import kotlinx.coroutines.flow.map
import retrofit2.http.Query
import javax.inject.Inject

/**
 *作者：lxy
 *功能:
 *时间：2025/6/1
 */
class PostListRepository @Inject constructor() {

    @Inject
    @MotoCircleNetModule.CommonMotoCircleApi
    lateinit var mApi: MotoCircleApi

    fun getPostInfo(
        pageNum: Int,
        pageSize: Int,
        isFocus: Int? = null,
        keyword: String? = null,
        memberId: String? = null,
        sortType: String? = null,
        topicId: String? = null
    ) = flow {
        emit(mApi.getPostInfo(pageNum, pageSize, isFocus, keyword, memberId, sortType, topicId))
    }.flowOn(Dispatchers.IO)


    fun queryPostPage(
        isFocus: Int? = null,
        keyword: String? = null,
        memberId: String? = null,
        sortType: String? = null,
        topicId: String? = null
    ) = Pager(
        config = PagingConfig(pageSize = 10),
        pagingSourceFactory = {
            PostPageSource(
                api = mApi,
                ifFocus = isFocus,
                keyword = keyword,
                memberId = memberId,
                sortType = sortType,
                topicId = topicId
            )
        })
        .flow

    /**
     *  检查是否关注
     */
    fun checkIfHasFocus() = flow {
        emit(mApi.checkIfHasFocus())
    }.flowOn(Dispatchers.IO)

    /**
     * 点赞帖子
     */
    fun giveLike(postsId: String) = flow {
        emit(mApi.giveValidationLike(postsId)) //校验帖子
    }.map {
        if (it.data) {//校验通过
            mApi.giveLike(postsId) //点赞和取消点赞
        } else {//校验不通过
            it
        }
    }.flowOn(Dispatchers.IO)
}